#include "LoginRunThread.h"
#include "xDef.h"
#include "xTime.h"
#include "Login.h"
bool LoginRunThread::Run()
{
    uint32 prevSleepTime = 0;
    uint32 curTime = 0;
    uint32 prevTime = xTime::GetCurTimeMs();
    while(!GetTermnation())
    {
        curTime = xTime::GetCurTimeMs();
        // t = tick , s = sleep 
        //diff = s0 + t0 , diff 是两次循环的间隔时间
        //希望一直保持 s1 + t1 = MAX_EPOLL_THREAD_TIMEOUT(100ms) , tick(t1)未知，但可以使用t0来作为参考值代替
        //s1 = MAX_EPOLL_THREAD_TIMEOUT - t1 = MAX_EPOLL_THREAD_TIMEOUT - t0 = MAX_EPOLL_THREAD_TIMEOUT - (diff - s0)
        uint32 diff = 0;
        if(prevTime > curTime)
        {
            diff = 0xFFFFFFFFFFFFFFFF - (prevTime - curTime);
        }
        else
        {
            diff = curTime - prevTime;
        }
        //如果运行时间大于固定的tick时间，则不sleep继续占用CPU来处理更新，直到能在一个tick处理所有操作为止，这个时候才会sleep让出CPU时间片
        if(diff <= MAX_EPOLL_THREAD_TIMEOUT + prevSleepTime) // diff - s0 = t0 >= MAX_EPOLL_THREAD_TIMEOUT
        {
            prevSleepTime = MAX_EPOLL_THREAD_TIMEOUT - (diff - prevSleepTime);
        }
        else
        {
            prevSleepTime = 0;
        }
        prevTime = curTime;
        LoginMgr.Update(diff);

        if(prevSleepTime > 0)
        {
            usleep(diff*1000);
        }
    }
    return true;
}